using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace SpoonStun.Message
{
	class PeerMessage : IStunMessage
	{
		private static int _count;
		public enum TypeValue : byte { Request, Response, Test }

		private int _id = _count++;
		private TypeValue _type;
		private IPEndPoint _peerEndPoint = new IPEndPoint(IPAddress.Any, 0);
		private IPEndPoint _peerSenderEndPoint = new IPEndPoint(IPAddress.Any, 0);

		public int MsgId
		{
			get { return 3; }
		}

		public int Id
		{
			get { return _id; }
			set { _id = value; }
		}

		public TypeValue Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public IPEndPoint PeerEndPoint
		{
			get { return _peerEndPoint; }
			set { _peerEndPoint = value; }
		}

		public IPEndPoint PeerSenderEndPoint
		{
			get { return _peerSenderEndPoint; }
			set { _peerSenderEndPoint = value; }
		}

		public void SetBytes(byte[] data)
		{
			BinaryReader br = new BinaryReader(new MemoryStream(data));

			Id = br.ReadInt32();
			Type = (TypeValue) br.ReadByte();
			PeerEndPoint = new IPEndPoint(new IPAddress(br.ReadBytes(4)), br.ReadInt32());
			PeerSenderEndPoint = new IPEndPoint(new IPAddress(br.ReadBytes(4)), br.ReadInt32());
		}

		public byte[] GetBytes()
		{
			MemoryStream stream = new MemoryStream();
			BinaryWriter bw = new BinaryWriter(stream);
			bw.Write(Id);
			bw.Write((byte)Type);
			bw.Write(PeerEndPoint.Address.GetAddressBytes());
			bw.Write(PeerEndPoint.Port);
			bw.Write(PeerSenderEndPoint.Address.GetAddressBytes());
			bw.Write(PeerSenderEndPoint.Port);
			return stream.ToArray();
		}
	}
}
